'use strict'

var
    auth_token = require("./auth_token"),
    auth_list = require("../auth_list.json"),
    des = require("../../des"),
    pako = require('pako'),
    RESTFUL_CODE = require('../../restful/lib/code/CODE'),
    typeis = require('type-is');
//校验访问接口的合法性
var sys_auth = function (req, res, next) {
    if (global.isDebug) {
        var data = req.param("data");
        if (data) {
            req.data = JSON.parse(data);
        }
        next();
    } else if (req.headers && (res.reqToken = req.headers.token) && (res.reqAuthToken = req.headers.auth_token)) {
        var $token = auth_list[req.headers.token];
        if (!$token) {//没有权限
            res.restful(RESTFUL_CODE.ACCESS403);
            return;
        } else if (auth_token.getAuthToken_5minute($token.token, (res.reqPrivateToken = $token.private_token)) !== req.headers.auth_token) {//接口已过期
            res.restful(RESTFUL_CODE.IS_EXPIRED);
            return;
        } else {
            console.log("访问者：" + JSON.stringify($token));
            //参数解密
            var data = req.param("data");
            if (data && typeis(req, 'multipart/form-data')) {//如果是文件提交的模式上传的参数讲进行urlcode解码
                data = decodeURI(data);
            }
            if (data) {
                req.data = JSON.parse(des.strDec(pako.inflate(data, {to: "string"}), $token.token, $token.private_token, req.headers.auth_token));
            }
            next();//认证通过
        }
    } else {
        res.restful(RESTFUL_CODE.ACCESS403);
        return;
    }
};

exports = module.exports = sys_auth;